window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;

function draw(origObjURL, orientation, targetImg) {
  var img = new Image();
  img.addEventListener('load', function(event) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    // switch width height if orientation needed
    if (orientation < 5) {
      canvas.width = img.width;
      canvas.height = img.height;
    } else {
      canvas.width = img.height;
      canvas.height = img.width;
    }

    // transform (rotate) image - see link at beginning this method
    switch (orientation) {
      case 2: ctx.transform(-1, 0, 0, 1, img.width, 0); break;
      case 3: ctx.transform(-1, 0, 0, -1, img.width, img.height); break;
      case 4: ctx.transform(1, 0, 0, -1, 0, img.height); break;
      case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
      case 6: ctx.transform(0, 1, -1, 0, img.height , 0); break;
      case 7: ctx.transform(0, -1, -1, 0, img.height, img.width); break;
      case 8: ctx.transform(0, -1, 1, 0, 0, img.width); break;
    }

    ctx.drawImage(img, 0, 0);
    // pass rotated image data to the target image container
    targetImg.src = canvas.toDataURL();
  }, false);

  img.src = origObjURL;
}